<?php
/**
 * 后台数据管理相关操作
 * 作者：刘单风
 * 最后修改时间：2016-12-23
 * 版权：刘单风个人所有
 */
namespace app\admin\controller;
use app\model\Wechatgroups;
use MoCommon\Services\UploadFiles;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Controller;
use think\facade\Config;
use think\facade\Env;
use think\Hook;

class Groupadmin extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
        Hook::listen('CheckAuth');
    }

    /**
     * 科室列表数据
     */
    public function depList($depid=0)
    {
        $groupModel = new Wechatgroups();

        if($depid){
            //获取此科室名称
            $depname=$groupModel->depdetail("id=$depid");
            $this->assign('depname', $depname);
            //科室下的疾病列表
            $deplist = $groupModel->depchild($depid);
            $datatype=1;
        }else{
            $deplist = $groupModel->deplist();
            $datatype=0;
        }
        $this->assign('datatype', $datatype);
        $this->assign('deplist', $deplist);
        return $this->fetch('deplist');
    }

    /**
     * 添加科室
     * @param int $id
     * @return mixed
     */
    public function addDep($id = 0,$datatype=0)
    {
        $groupModel = new Wechatgroups();
        $depdata = ['id' => 0, 'dep_name' => '', 'father_id' => 0, 'data_type' => $datatype];
        if ($id) {
            $depdata = $groupModel->depdetail(['id' => $id]);
        }
        if ($datatype) {
            //获取二级科室信息
            if ($id) {
                $twodep = $groupModel->depdetail(['id' => $depdata['father_id']]);
                $depdata['tfdepid'] = $depdata['father_id'];
                $depdata['father_id'] = $twodep['father_id'];
                $twodeps = $groupModel->depchild($twodep['father_id']);
            } else {
                $depdata['tfdepid'] = 0;
                $depdata['father_id'] = 0;
                $twodeps = null;
            }
            $this->assign('tfdeps', $twodeps);

        }
        //获取一级大类数据信息
        $fdeps = $groupModel->deplist(1);
        $this->assign('fdeps', $fdeps);
        $this->assign('depdetail', $depdata);
        return $this->fetch('depdetail');
    }

    /**
     * 科室保存
     */
    public function doAddDep()
    {
        $groupModel = new Wechatgroups();
        //查询是否存在
        $where = [
            'dep_name' => $_POST['depname'],
            'father_id' => $_POST['fatherid']
        ];
        if ($_POST['id']) {
            $where['id'] = "!=" . $_POST['id'];
        }
        $data = $groupModel->depdetail($where);
        if ($data) {
            $this->error('该科室已经存在，请重新输入', '/wechatgroup/depadd');
        } else {
            $insrtdata = [
                'dep_name' => $_POST['depname'],
                'father_id' => $_POST['fatherid'],
                'data_type'=>$_POST['datatype']
            ];
            if ($_POST['id']) {
                $groupModel->depupdate($insrtdata, ['id' => $_POST['id']]);
            } else {
                $groupModel->depinsert($insrtdata);
            }
            $this->success('保存成功', '/wechatgroup/deps');
        }
    }

    /**
     * 删除科室
     * @param $id
     */
    public function delDep($id)
    {
        $groupModel = new Wechatgroups();
        $groupModel->depdelete($id);
        $this->success('删除成功', '/wechatgroup/deps');
    }

    /**
     * 城市列表数据
     */
    public function cityList()
    {
        $keywords=input('keywords','');
        $groupModel = new Wechatgroups();
        $where="1=1";
        if($keywords){
            $where="city_name like '%$keywords%'";
        }
        $citydata = $groupModel->citylist($where);
        $this->assign('citydata', $citydata);
        $this->assign('keywords', $keywords);
        return $this->fetch('citylist');
    }

    //城市操作
    public function cityOper()
    {
        $isshow = input('isshow');
        $cityid = input('cityid');
        $groupModel = new Wechatgroups();
        $data = array(
            'is_show' => $isshow
        );
        $groupModel->cityOper($data, ['id' => $cityid]);
        echo json_encode(0);
    }

    //微信群列表
    public function wechatList()
    {
        $keywords = input('keywords', '');
        $datatype = input('datatype', 0);
        $groupModel = new Wechatgroups();
        $groupdata = $groupModel->groupList("group_name like '%$keywords%' and data_type=$datatype");
        $this->assign('keywords', $keywords);
        $this->assign('datatype', $datatype);
        $this->assign('groupdata', $groupdata);
        return $this->fetch('grouplist');
    }

    //微信群详情
    public function groupDetail($id = 0)
    {
        $groupModel = new Wechatgroups();
        if ($id) {
            $detail = $groupModel->groupDetail(['id' => $id]);
        }else{
            $detail=[
                'id'=>0,
                'group_name'=>'',
                'group_img'=>'',
                'fdep_id'=>0,
                'dep_id'=>0,
                'dis_id'=>0,
                'prov_id'=>0,
                'city_id'=>0,
                'group_notice'=>'',
                'code_img'=>'',
                'scan_num'=>0,
                'helper_code_img'=>'',
                'data_type'=>0,
            ];
        }
        $this->assign('groupdetail', $detail);
        //一级科室信息
        $deplist = $groupModel->deplist(1);
        //获取第一个科室的子级科室
        $depid=$detail['fdep_id']?:$deplist[0]['id'];
        $depchild = $groupModel->depchild($depid);
        //获取第一个子级科室的疾病信息
        $twodep=$detail['dep_id']?:$depchild[0]['id'];
        $dischild = $groupModel->depchild($twodep);
        $this->assign('deplist', $deplist);
        $this->assign('depchild', $depchild);
        $this->assign('dischild', $dischild);
        //获取省份信息
        $pros = $groupModel->citydata("father_id=0");
        $this->assign('pros', $pros);
        //获取第一个省的城市信息
        $prvid=$detail['prov_id']?:-1;
        $citys = $groupModel->citydata("father_id=" . $prvid);
        $this->assign('citys', $citys);
        return $this->fetch('groupdetail');
    }

    //微信群信息保存
    public function doAddgroup()
    {
        $groupModel = new Wechatgroups();
        //查询是否存在
        $where = [
            'group_name' => $_POST['groupname'],
            'dep_id' => $_POST['depid'],
            'prov_id' => $_POST['provid'],
            'city_id' => $_POST['cityid'],
            'data_type' => $_POST['datatype']
        ];
        if ($_POST['id']) {
            $where['id'] = "!=" . $_POST['id'];
        }
        $data = $groupModel->groupDetail($where);
        if ($data) {
            $this->error('该微信群已经存在，请重新输入', '/wechatgroup/groupadd');
        } else {
            $insrtdata = [
                'group_name' => $_POST['groupname'],
                'group_img' => $_POST['groupimg'],
                'group_notice' => $_POST['groupnotice'],
                'dep_id' => $_POST['depid'],
                'dis_id' => $_POST['disid'],
                'prov_id' => $_POST['provid'],
                'city_id' => $_POST['cityid'],
                'data_type' => $_POST['datatype'],
                'is_hot' => $_POST['ishot'],
                'scan_num' => $_POST['scannum'],
                'code_img' => $_POST['codeimg'],
                'helper_code_img' => $_POST['helpercodeimg']
            ];
            if ($_POST['id']) {
                $data = $groupModel->groupDetail(['id' => $_POST['id']]);
                //查看之前是否有封面图
                if ($data['group_img'] && $insrtdata['group_img'] != $data['group_img']) {
                    //说明是更新封面图,删除之前的封面图
                    $img = explode("wechatgroupimgs", $data['group_img']);
                    $this->delPic($img[1]);
                }
                if ($data['code_img'] && $insrtdata['code_img'] != $data['code_img']) {
                    //更新二维码过期时间
                    $deadline = strtotime("+1week", strtotime(date('Y-m-d')));
                    $deadline = $deadline;
                    $insrtdata['deadline'] = $deadline;
                    //说明是更新二维码图,删除之前的二维码图
                    $img = explode("wechatgroupimgs", $data['code_img']);
                    $this->delPic($img[1]);
                }
                if ($data['helper_code_img'] && $insrtdata['helper_code_img'] != $data['helper_code_img']) {
                    //说明是更新群助手二维码,删除之前的群助手二维码
                    $img = explode("wechatgroupimgs", $data['helper_code_img']);
                    $this->delPic($img[1]);
                }
                $groupModel->groupUpdate($insrtdata, ['id' => $_POST['id']]);
                $groupid = $_POST['id'];
            } else {
                $insrtdata['create_time'] = time();
                $deadline = strtotime("+1week", strtotime(date('Y-m-d')));
                $deadline = $deadline;
                $insrtdata['deadline'] = $deadline;
                $groupid = $groupModel->groupInsert($insrtdata);
            }
            $this->success('保存成功', '/wechatgroup/wechatlist');
        }
    }

    //科室/城市更换选择读取子级数据
    public function datachange()
    {
        $groupModel = new Wechatgroups();
        $datatype = input('datatype', 0);
        $dataid = input('dataid', 0);
        if ($datatype == 0||$datatype==2) {
            //去读科室子级数据
            $data = $groupModel->depchild($dataid);
        } else {
            //城市子级数据
            //获取第一个省的城市信息
            $data = $groupModel->citydata("father_id=" . $dataid);
        }
        echo json_encode($data);
        exit();
    }

    //删除群组
    public function delgroup($id)
    {
        $groupModel = new Wechatgroups();
        $data = $groupModel->groupDetail(['id' => $id]);
        //查看之前是否有封面图
        if ($data['group_img']) {
            //说明是更新封面图,删除之前的封面图
            $img = explode("wechatgroupimgs", $data['group_img']);
            $this->delPic($img[1]);
        }
        if ($data['code_img']) {
            //说明是更新封面图,删除之前的封面图
            $img = explode("wechatgroupimgs", $data['code_img']);
            if(count($img)>=2&&$img[1]){
                $this->delPic($img[1]);
            }
        }
        if ($data['helper_code_img']) {
            //说明是更新封面图,删除之前的封面图
            $img = explode("wechatgroupimgs", $data['helper_code_img']);
            $this->delPic($img[1]);
        }
        $groupModel->groupDel($id);
        $this->success('删除成功', '/wechatgroup/wechatlist');
    }

    //banner列表数据
    public function bannerList()
    {
        $groupModel = new Wechatgroups();
        $banner=$groupModel->bannerList();
        $this->assign('banners', $banner);
        return $this->fetch('bannerlist');
    }

    //banner详情
    public function bannerDetail($id=0)
    {
        $groupModel = new Wechatgroups();
        if ($id) {
            $detail = $groupModel->bannerdetail("id=$id");
        }else{
            $detail=[
                'id'=>0,
                'banner_name'=>"",
                'banner_img'=>"",
                'data_type'=>0,
                'banner_msg'=>""
            ];
        }
        $this->assign('detail', $detail);
        return $this->fetch('bannerdetail');
    }

    //banner保存
    public function doAddbanner()
    {
        $groupModel = new Wechatgroups();
        //查询是否存在
        $where = [
            'banner_name' => $_POST['bannername'],
            'data_type' => $_POST['datatype']
        ];
        if ($_POST['id']) {
            $where['id'] = "!=" . $_POST['id'];
        }
        $data = $groupModel->bannerdetail($where);

        if ($data) {
            $this->error('该banner数据已经存在，请重新输入', '/wechatgroup/banneradd');
        } else {
            $insrtdata = [
                'banner_name' => $_POST['bannername'],
                'banner_img' => $_POST['bannerimg'],
                'banner_msg' => isset($_POST['bannermsg'])?$_POST['bannermsg']:"",
                'data_type' => $_POST['datatype']
            ];
            if ($_POST['id']) {
                $data = $groupModel->bannerdetail(['id' => $_POST['id']]);
                //查看之前是否有banner图
                if ($data['banner_img'] && $insrtdata['banner_img'] != $data['banner_img']) {
                    //说明是更新封面图,删除之前的banner图
                    $img = explode("wechatgroupimgs", $data['banner_img']);
                    $this->delPic($img[1]);
                }
                $groupModel->bannerUpdate($insrtdata, ['id' => $_POST['id']]);
                $bannerid = $_POST['id'];
            } else {
                $insrtdata['create_time'] = time();
                $bannerid = $groupModel->bannerInsert($insrtdata);
            }
            $this->success('保存成功', '/wechatgroup/banners');
        }
    }

    //删除banner数据
    public function delbanner($id)
    {
        $groupModel = new Wechatgroups();
        $data = $groupModel->bannerdetail(['id' => $id]);
        //查看之前是否有banner图
        if ($data['banner_img']) {
            //删除之前的banner图
            $img = explode("wechatgroupimgs", $data['banner_img']);
            $this->delPic($img[1]);
        }
        $groupModel->bannerDel($id);
        $this->success('删除成功', '/wechatgroup/banners');
    }

    //上传图片
    public function uploadFiles()
    {
        $imgfiletype = input('imgfiletype');
        if ($imgfiletype==1) {
            $webtag="groupimg";
            $file = $_FILES['groupimgfile'];
        }else if($imgfiletype==2){
            $webtag="codeimg";
            $file = $_FILES['codeimgfile'];
        }else if($imgfiletype==3){
            $webtag="helpercodeimg";
            $file = $_FILES['helpercodeimgfile'];
        }else if($imgfiletype==4){
            $webtag="bannerimg";
            $file = $_FILES['bannerimgfile'];
        }
        //将文件上传到本地
        $picname = UploadFiles::singlefileupload('', $file, Env::get('ROOT_PATH') . 'public/temp/', '');
        $alioss = Config::get('app.alioss');
        $accessKeyId = $alioss['accesskey'];
        $accessKeySecret = $alioss['accesskeysecret'];
        $endpoint = $alioss['endpoint'];
        // 存储空间名称
        $bucket = $alioss['bucket'];
        // 文件名称
        $object = "wechatgroupimgs/$picname";
        $filePath = Env::get('ROOT_PATH') . 'public/temp/' . $picname;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch (OssException $e) {
            //文件上传失败
        } finally {
            //删除服务器上的临时文件
            unlink($filePath);
        }

        $prizeimg = "https://medi-community.oss-cn-beijing.aliyuncs.com/" . $object;
        echo "<p style='color:red'>上传成功！</p>";
        echo "<script>window.parent.document.getElementById('$webtag').value='" . $prizeimg . "';</script>";
        exit();
    }

    //阿里云删除图片
    public function delPic($imgname)
    {
        $alioss = Config::get('app.alioss');
        $accessKeyId = $alioss['accesskey'];
        $accessKeySecret = $alioss['accesskeysecret'];
        $endpoint = $alioss['endpoint'];
        // 存储空间名称
        $bucket = $alioss['bucket'];
        // 文件名称
        $object = "wechatgroupimgs" . $imgname;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->deleteObject($bucket, $object);
        } catch (OssException $e) {
            //文件删除失败
        }
    }

}
